package intranet.server;
/**
 * @author Baptiste RENDU
 */
import intranet.client.AddUserService;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class AddUserServiceImpl extends RemoteServiceServlet implements
		AddUserService {
	Connection connect = null;
	/**
	 * methode de connexion a la base de données
	 * @return true si la connexion s'est bien effectuée, false sinon
	 */
	public boolean connect() {
		
		try {
		    Class.forName("org.postgresql.Driver");
	 
		  } catch (ClassNotFoundException e) {
		    System.out.println("Can't find the JDBC driver in your path!");
		    e.printStackTrace();
		    return false;
		  }
	 
		  System.out.println("PostgreSQL JDBC driver loaded!");
	
	 
		  try {
	 
			  connect = DriverManager.getConnection("jdbc:postgresql:intranet-grpc","postgres", "grpc");
	 
		  } catch (SQLException e) {
		    System.out.println("Connection Failed!");
		    e.printStackTrace();
		    return false;
		  }
		  return true;
	}
	
	/**
	 * methode de deconnexion a la base de données
	 * @return true if succeed
	 * @return false if not
	 */
	public boolean disconnect()
	  {
	      try{
	          connect.close();
	       return true;
	          } catch (Exception e){}
	          return false;
	  }
	/**
	 * methode d'ajout d'utilisateur dans la base de donnée
	 * @return true si l'ajout est bien effectuée, false sinon
	 */
	@Override
	public boolean addUser(String login, String name, String firstname, int status, double quota) {
		// TODO Auto-generated method stub
		
		String grainOfSalt="123";
		MessageDigest m=null;
		try {
			m = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		m.reset();
		m.update((login + grainOfSalt).getBytes());
		byte[] digest = m.digest();
		BigInteger bigInt = new BigInteger(1, digest);
		String encryptedPassword = bigInt.toString(16);

		while (encryptedPassword.length() < 32) {
			encryptedPassword = "0" + encryptedPassword;
		}
		Statement state=null; 
		 int x=-2;
		 if (connect())
		 {
		 try{
			 state=connect.createStatement();
			 x=state.executeUpdate("INSERT INTO teacher (teacher_name,teacher_firstname,teacher_login,teacher_password,teacher_grainofsalt,teacher_status,teacher_quota) VALUES ('"+name+"','"+firstname+"','"+login+"','"+encryptedPassword+"','"+grainOfSalt+"',"+status+","+quota+")",Statement.RETURN_GENERATED_KEYS);
			 ResultSet rs = state.getGeneratedKeys();
			 if (rs.next())
			 {
				 x=rs.getInt(1);
			 }
		 }
		 catch (Exception e)
		 {
			 System.out.println("Erreur lors du insert");
			 e.printStackTrace();
		 }
		 disconnect();
		 }
		
		if(x>0)
			return true;
		return false;
	}
}